package com.xuecheng.media.service.jobHandler;

import com.xuecheng.base.utils.Mp4VideoUtil;
import com.xuecheng.media.model.po.MediaProcess;
import com.xuecheng.media.service.MediaFileProcessService;
import com.xuecheng.media.service.MediaFileService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
视频处理任务类
 */
@Slf4j
@Component
public class VideoTask {

    @Autowired
    MediaFileProcessService mediaFileProcessService;

    @Autowired
    MediaFileService mediaFileService;

    @Value("${videoprocess.ffmpegpath}")
    String ffmpegpath;

    @XxlJob("videoJobHandler")
    public void videoJobHandler() throws Exception {
        //分片参数
        int shardIndex=XxlJobHelper.getShardIndex();//执行的序号 从0开始
        int shardTotal=XxlJobHelper.getShardTotal();

        int processors = Runtime.getRuntime().availableProcessors();
        //查询待处理任务
        List<MediaProcess> mediaProcessList = mediaFileProcessService.getMediaProcessList(shardIndex, shardTotal, processors/2);

        //任务数量
        int size = mediaProcessList.size();
        if(size<=0){
            log.debug("取到的视频任务数量{}",size);
            return;
        }
        //创建线程池
        ExecutorService executorService = Executors.newFixedThreadPool(size);
        //使用计数器
        CountDownLatch countDownLatch = new CountDownLatch(size);
        mediaProcessList.forEach(mediaProcess -> {
            //加入线程池
            executorService.execute(()->{
                try{
                    Long taskId = mediaProcess.getId();
                    String fileId = mediaProcess.getFileId();
                    //开启任务 拿锁
                    boolean b = mediaFileProcessService.startTask(taskId);
                    if(!b){
                        log.debug("抢占任务失败，任务id{}",taskId);
                        return;
                    }
                    //执行视频转码

                    //下载视频到本地
                    String bucket = mediaProcess.getBucket();
                    String objectName = mediaProcess.getFilePath();
                    File file = mediaFileService.downloadFileFromMinIO(bucket, objectName);
                    if(file==null){
                        log.debug("下载视频出错，任务id:{},buket:{},objectName:{}",taskId,bucket,objectName);
                        mediaFileProcessService.saveProcessFinishStatus(taskId,"3",fileId,null,"下载视频到本地失败");
                        return;
                    }

                    //源avi视频的路径
                    String video_path = file.getAbsolutePath();
                    //转换后mp4文件的名称
                    String mp4_name = fileId+".mp4";
                    //先创建一个临时文件
                    File mp4File=null;
                    try{
                        mp4File = File.createTempFile("minio", ".mp4");
                    } catch (IOException e) {
                        log.debug("创建临时文件异常,{}",e.getMessage());
                        mediaFileProcessService.saveProcessFinishStatus(taskId,"3",fileId,null,"创建临时文件异常");
                        return;
                    }
                    String mp4_path = mp4File.getAbsolutePath();
                    //创建工具类对象
                    Mp4VideoUtil videoUtil = new Mp4VideoUtil(ffmpegpath,video_path,mp4_name,mp4_path);
                    //开始视频转换，成功将返回success
                    String result = videoUtil.generateMp4();
                    if(!result.equals("success")){
                        log.debug("视频转码失败，原因:{},buket:{},objectName:{}",result,bucket,objectName);
                    }
                    String objectNameForMP4 = getFilePathByMd5(fileId, ".mp4");
                    //上传到Minio
                    boolean b1 = mediaFileService.addMediaFilesToMinIO(mp4File.getAbsolutePath(), "video/mp4", bucket, objectNameForMP4);
                    if(!b1){
                        log.debug("上传mp4到minio失败,taskID{}",taskId);
                        mediaFileProcessService.saveProcessFinishStatus(taskId,"3",fileId,null,"上传mp4到minio失败");
                        return;
                    }

                    //MP4 url
                    String url = "/"+bucket+"/"+objectNameForMP4;
                     //保存任务的处理结果
                    mediaFileProcessService.saveProcessFinishStatus(taskId,"2",fileId,url,"任务成功");
                }
                finally {
                    countDownLatch.countDown();
                }

            });

        });

        //阻塞线程 等所有线程 再结束方法
        countDownLatch.await(30, TimeUnit.MINUTES);

    }


    private String getFilePathByMd5(String fileMd5,String fileExt){
        return   fileMd5.substring(0,1) + "/" + fileMd5.substring(1,2) + "/" + fileMd5 + "/" +fileMd5 +fileExt;
    }

}
